﻿using AutoMapper;
using Max.PH6_2006A.LowCode.Domain;
using Max.PH6_2006A.LowCode.DTO;
using Max.PH6_2006A.LowCode.IRespository;
using Max.PH6_2006A.LowCode.IService;
using System.Data;
using System.IdentityModel.Tokens.Jwt;

namespace Max.PH6_2006A.LowCode.Service
{
    public class SystemUserService : BaseService<SystemUser,
                                                 SystemUserInputDto,
                                                 SystemUserOutputDto>,
                                     ISystemUserService
    {

        IMapper _map; //引用Automapper对象

        ISystemUserRespository _respository;
        ISystemMenuRespository _menuRespository;
        ISystemUserRoleRespository _userRoleRespository;
        public SystemUserService(ISystemUserRespository respository, IMapper map,
            ISystemMenuRespository menuRespository, ISystemUserRoleRespository userRoleRespository) : base(respository, map)
        {
            _respository = respository;
            _map = map;

            _menuRespository = menuRespository;
            _userRoleRespository = userRoleRespository;
        }

        /// <summary>
        /// 根据用户ID，获取权限菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IEnumerable<SystemMenu>> GetMenuByUserIdAsync(string id)
        {
            string sql = "select u.LoginName, u.NickName ";
            sql += ", m.ID ";
            sql += ",m.FatherId ";
            sql += ",m.[Name] ";
            sql += ",m.[Url] ";
            sql += ",m.Icon ";
            sql += "from SystemUser u ";
            sql += "left join SystemUserRole ur on u.ID = ur.UserID ";
            sql += "left join SystemRoleMenu rm on ur.RoleID = rm.RoleID ";
            sql += "left join SystemMenu m on rm.MeunID = m.ID ";
            sql += $"where u.ID = @id order by m.sort";

            var menus = await  _menuRespository.QueryAsync(sql, new { id = id });

            return menus;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Tuple<bool, SystemUser, string>> LoginAsync(SystemUserLoginDto dto)
        {
            try
            {
                //dto.Password = MD5Hash.Hash.Content(dto.Password);

                string sql = $"select * from SystemUser where LoginName=@UserName and Password =@Password";

                var result = await _respository.QueryAsync(sql, dto);

                if (result == null || result.Count() <= 0)
                    return Tuple.Create<bool, SystemUser, string>(false, null, "用户名或密码错误！");

                var d = result.FirstOrDefault();
                ////判断用户状态
                //if(d.Statue == null || !d.Statue.Equals("0"))
                //    return Tuple.Create<bool, SystemUser, string>(false, null, "该用户已被禁用，请与管理员联系！");


                //生成token
                var token = CreateToken(d.LoginName);

                return Tuple.Create(true, d, token);
            }
            catch (Exception ex)
            {
                return Tuple.Create<bool, SystemUser, string>(false, null, ex.Message);
            }
        }


        private string CreateToken(string username)
        {

            System.Security.Claims.Claim[] claims = new System.Security.Claims.Claim[] {
                 new System.Security.Claims.Claim("UserName",username)
            };

            string customKey = "aflasjdfl;asfjlas;fdjlasfjas90834salfdasjlfsajflasfas";
            byte[] bt = System.Text.ASCIIEncoding.UTF8.GetBytes(customKey);

            Microsoft.IdentityModel.Tokens.SecurityKey key = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(bt);

            Microsoft.IdentityModel.Tokens.SigningCredentials signingCredentials
                = new Microsoft.IdentityModel.Tokens.SigningCredentials(key, "HS512");

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: "梁才根", //签发人
                audience: "任何人", //受众
                claims: claims, //声明
                notBefore: DateTime.Now, //这在个日期之前是无效的
                expires: DateTime.Now.AddHours(2),//过期时间（2小时）             
                signingCredentials: signingCredentials //签名
            );

            var str = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().WriteToken(token);
            return str;
        }


        /// <summary>
        /// 用户配置角色
        /// </summary>
        /// <param name="userRoles"></param>
        /// <returns></returns>
        public async Task<int>  UserConfigRoleAsync(List<SystemUserRole> userRoles)
        {
            Dictionary<string, object> sqls = new();

            sqls.Add("delete from SystemUserRole where UserId=@UserId", new { UserId = userRoles[0].UserId });
            sqls.Add("insert into SystemUserRole(userid,roleid) values(@UserId,@RoleId)", userRoles);
            int result = await _respository.ExecuteSqlMuitple(sqls);
            return result;
        }

        public async Task<int> InsertUserAndRoleAsync(SystemUser user,List<SystemUserRole> userRoles)
        {
            Dictionary<string, object> sqls = new();

            //插入到用户表
            sqls.Add("insert into SystemUser(loginname,password,nickname) values(@LoginName,@Password,@NickName)", user);

            //插入到用户角色表
            sqls.Add("insert into SystemUserRole(userid,roleid) values(@UserId,@RoleId)", userRoles);
            int result = await _respository.ExecuteSqlMuitple(sqls);
            return result;
        }
    }
}